package com.babyqiao.wallpaper.portal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.babyqiao.wallpaper.exceptionhandler.WallpaperException;
import com.babyqiao.wallpaper.portal.service.AuthService;
import com.babyqiao.wallpaper.portal.service.UmsMemberCacheService;
import com.babyqiao.wallpaper.portal.service.UmsMemberService;
import com.babyqiao.wallpaper.portal.utils.common.DefaultPasswordEnum;
import com.babyqiao.wallpaper.portal.utils.common.HttpsClientRequestFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.api.ResultCode;
import com.macro.mall.common.constant.AuthConstant;
import com.macro.mall.common.domain.UserDto;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.mapper.UmsMemberLevelMapper;
import com.macro.mall.mapper.UmsMemberMapper;
import com.macro.mall.model.UmsMember;
import com.macro.mall.model.UmsMemberExample;
import com.macro.mall.model.UmsMemberLevel;
import com.macro.mall.model.UmsMemberLevelExample;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 会员管理Service实现类
 * Created by macro on 2018/8/3.
 */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UmsMemberServiceImpl.class);
    @Autowired
    private UmsMemberMapper memberMapper;
    @Autowired
    private UmsMemberLevelMapper memberLevelMapper;
    @Autowired
    private UmsMemberCacheService memberCacheService;
    @Value("${redis.key.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    @Value("${redis.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;
    @Value("${spring.wxminiprogram.appid}")
    private String appid;
    @Value("${spring.wxminiprogram.secret}")
    private String secret;

    ObjectMapper om = new ObjectMapper();
    @Autowired
    private AuthService authService;
    @Autowired
    private HttpServletRequest request;

    @Override
    public UmsMember getByUsername(String username) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            return memberList.get(0);
        }
        return null;
    }

    @Override
    public UmsMember getById(Long id) {
        return memberMapper.selectByPrimaryKey(id);
    }

    @Override
    public void register(String username, String password, String telephone, String authCode) {
        //验证验证码
        if(!verifyAuthCode(authCode,telephone)){
            Asserts.fail("验证码错误");
        }
        //查询是否已有该用户
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        example.or(example.createCriteria().andPhoneEqualTo(telephone));
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(umsMembers)) {
            Asserts.fail("该用户已经存在");
        }
        //没有该用户进行添加操作
        UmsMember umsMember = new UmsMember();
        umsMember.setUsername(username);
        umsMember.setPhone(telephone);
        umsMember.setPassword(BCrypt.hashpw(password));
        umsMember.setCreateTime(new Date());
        umsMember.setStatus(1);
        //获取默认会员等级并设置
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria().andDefaultStatusEqualTo(1);
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        if (!CollectionUtils.isEmpty(memberLevelList)) {
            umsMember.setMemberLevelId(memberLevelList.get(0).getId());
        }
        memberMapper.insert(umsMember);
        umsMember.setPassword(null);
    }

    @Override
    public String generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for(int i=0;i<6;i++){
            sb.append(random.nextInt(10));
        }
        memberCacheService.setAuthCode(telephone,sb.toString());
        return sb.toString();
    }

    @Override
    public void updatePassword(String telephone, String password, String authCode) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andPhoneEqualTo(telephone);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(memberList)){
            Asserts.fail("该账号不存在");
        }
        //验证验证码
        if(!verifyAuthCode(authCode,telephone)){
            Asserts.fail("验证码错误");
        }
        UmsMember umsMember = memberList.get(0);
        umsMember.setPassword(BCrypt.hashpw(password));
        memberMapper.updateByPrimaryKeySelective(umsMember);
        memberCacheService.delMember(umsMember.getId());
    }

    @Override
    public UmsMember getCurrentMember() {
        String userStr = request.getHeader(AuthConstant.USER_TOKEN_HEADER);
        if(StrUtil.isEmpty(userStr)){
            Asserts.fail(ResultCode.UNAUTHORIZED);
        }
        UserDto userDto = JSONUtil.toBean(userStr, UserDto.class);
        UmsMember member = memberCacheService.getMember(userDto.getId());

        if(member!=null){
            member.setOpenid("");
            return member;
        }else{
            member = getById(userDto.getId());
            memberCacheService.setMember(member);
            member.setOpenid("");
            return member;
        }
    }

    @Override
    public void updateIntegration(Long id, Integer integration) {
        UmsMember record=new UmsMember();
        record.setId(id);
        record.setIntegration(integration);
        memberMapper.updateByPrimaryKeySelective(record);
        memberCacheService.delMember(id);
    }

    @Override
    public UserDto loadUserByUsername(String username) {
        UmsMember member = getByUsername(username);
        if(member!=null){
            UserDto userDto = new UserDto();
            BeanUtil.copyProperties(member,userDto);
            userDto.setRoles(CollUtil.toList("前台会员"));
            return userDto;
        }
        return null;
    }

    /**
     *登录后获得token
     * @Author QLZ
     * @Date 2021/2/23
     *  @param principal: 代表一个认证实体，这里可以是 用户名，邮箱，手机号
     @param password: 密码
      *  @return: com.macro.mall.common.api.CommonResult
     */
    @Override
    public CommonResult login(String principal, String password) {
        if(StrUtil.isEmpty(principal)||StrUtil.isEmpty(password)){
            Asserts.fail("登录名或密码不能为空！");
        }
        //根据传过来的实体查询出用户名
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(principal);
        example.or(example.createCriteria().andPhoneEqualTo(principal));
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(umsMembers)) {
            Asserts.fail("用户不存在");
        }
        Map<String, String> params = new HashMap<>();
        params.put("client_id", AuthConstant.PORTAL_CLIENT_ID);
        params.put("client_secret","123456");
        params.put("grant_type","password");
        params.put("username",umsMembers.get(0).getUsername());
        params.put("password",password);
        return authService.getAccessToken(params);
    }

    /**
     * 微信小程序登录
     *
     * @param code : 授权码
     * @Author QLZ
     * @Date 2021/2/22
     * @return: java.lang.String
     */
    @Override
    public CommonResult loginBywxMiniProgramService(String code) throws JsonProcessingException {

        RestTemplate rest = new RestTemplate(new HttpsClientRequestFactory());
        //HttpResponseVo forObject = rest.getForObject("https://api.weixin.qq.com/sns/jscode2session?appid={1}&secret={2}&js_code={3}&grant_type=authorization_code", HttpResponseVo.class, appid,secret,code);
        ResponseEntity<String> forEntity =
                rest.getForEntity("https://api.weixin.qq.com/sns/jscode2session?appid={1}&secret={2}&js_code={3}&grant_type=authorization_code",
                        String.class, appid, secret, code);
        Map map1 = om.readValue(forEntity.getBody(), Map.class);
        //如果返回值中包含错误信息。抛出错误的相关异常
        if (map1.containsKey("errcode")) {
            throw new WallpaperException((Integer) map1.get("errcode"), (String) map1.get("errmsg"));

        }
        System.out.println("openid  "+ map1.get("openid"));
        //queryWrapper.eq("openid", (String) map1.get("openid"));

        //查询是否已有该用户
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andOpenidEqualTo((String) map1.get("openid"));
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        //如果用户存在直接返回token
        if (!CollectionUtils.isEmpty(umsMembers)) {
            //return JwtUtils.getJwtToken(umsMembers.get(0).getId().toString(), null);
            //构建登录参数
            Map<String, String> params = new HashMap<>();
            params.put("client_id", AuthConstant.PORTAL_CLIENT_OTHER_ID);
            params.put("client_secret","123456");
            params.put("grant_type","password");
            params.put("username",umsMembers.get(0).getOpenid());
            params.put("password", DefaultPasswordEnum.MP_PASS.getKey());
            return authService.getAccessToken(params);
            //return null;
        }

        //根据openid查询数据表
//        UcenterUser result = baseMapper.selectOne(queryWrapper);
//        //如果查询有值 直接返回openid
//        if (result != null) {
//            return JwtUtils.getJwtToken(result.getId(), null);
//            // return result.getOpenId();
//        }


        //没有该用户进行添加操作
        UmsMember umsMember = new UmsMember();
        umsMember.setOpenid((String) map1.get("openid"));
        umsMember.setUsername((String) map1.get("openid"));
        umsMember.setCreateTime(new Date());
        umsMember.setStatus(1);
        //获取默认会员等级并设置
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria().andDefaultStatusEqualTo(1);
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        if (!CollectionUtils.isEmpty(memberLevelList)) {
            umsMember.setMemberLevelId(memberLevelList.get(0).getId());
        }
        memberMapper.insert(umsMember);

        //构建登录参数
        Map<String, String> params = new HashMap<>();
        params.put("client_id", AuthConstant.PORTAL_CLIENT_OTHER_ID);
        params.put("client_secret","123456");
        params.put("grant_type","password");
        params.put("username",umsMember.getOpenid());
        params.put("password",DefaultPasswordEnum.MP_PASS.getKey());
        return authService.getAccessToken(params);
        //return null;


    }

    /**
     * 根据openid获取用户信息
     *
     * @param openid
     */
    @Override
    public UserDto loadUserByOpenid(String openid) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andOpenidEqualTo(openid);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {

                UserDto userDto = new UserDto();
                userDto.setId(memberList.get(0).getId());
                //openId的登录方式将用户名设置为openid,密码设置为空，这样不破坏整体的认证方式
                userDto.setUsername(memberList.get(0).getOpenid());
                userDto.setPassword(DefaultPasswordEnum.MP_PASS.getCiphertext());
                userDto.setStatus(memberList.get(0).getStatus());
               // BeanUtil.copyProperties(memberList.get(0),userDto);
                userDto.setRoles(CollUtil.toList("前台会员"));
                return userDto;

        }
        return null;
    }


    //对输入的验证码进行校验
    private boolean verifyAuthCode(String authCode, String telephone){
        if(StringUtils.isEmpty(authCode)){
            return false;
        }
        String realAuthCode = memberCacheService.getAuthCode(telephone);
        return authCode.equals(realAuthCode);
    }

}
